﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RemotingLogServer.cs" company="">
//   
// </copyright>
// <summary>
//   The remoting log server.
// </summary>
// --------------------------------------------------------------------------------------------------------------------


using System;
using System.Collections;
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels;
using System.Runtime.Remoting.Channels.Ipc;
using System.Runtime.Serialization.Formatters;
using Systemathics.FrameWork.Interfaces;

namespace Systemathics.FrameWork
{
    [Serializable]
    public sealed class RemotingLogServer
    {
        private readonly LogMessage m_LogMessage;

        public RemotingLogServer()
        {
            try
            {
                var serverProv = new BinaryServerFormatterSinkProvider {TypeFilterLevel = TypeFilterLevel.Full};
                var clientProv = new BinaryClientFormatterSinkProvider();

                var properties = new Hashtable();
                properties["portName"] = "MessageServer";
                var ipc = new IpcChannel(properties, clientProv, serverProv);
                ChannelServices.RegisterChannel(ipc, false);
                RemotingConfiguration.RegisterWellKnownServiceType(typeof (LogMessage), "MessageServer.rem", WellKnownObjectMode.Singleton);
                m_LogMessage = (LogMessage) Activator.GetObject(typeof (LogMessage), "ipc://MessageServer/MessageServer.rem");
            }
            catch
            {
            }
        }
         
        public LogMessage LogMessage
        {
            get { return m_LogMessage; }
        }
    }

    public class LogMessage : MarshalByRefObject, ILogMessage
    {
        #region ILogMessage Members


        public void Trace(FireMessageEventArgs message)
        {
            if (OnMessageReceived != null && OnMessageReceived.GetInvocationList().Length > 0)
                OnMessageReceived(this, message);
        }

        #endregion

        public event EventHandler<FireMessageEventArgs> OnMessageReceived;

        public override object InitializeLifetimeService()
        {
            return null;
        }
    }
}